package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.geniuseoe2012.lazyloaderdemo.cache.ImageLoader;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.AnimaAccess;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.player.http.DownLoadFile;
import com.shoujifeng.snowmusic.player.http.DownloadManager;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.DownloadInterface;
import com.shoujifeng.snowmusic.player.interfaces.MoreInterface;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DownLoadIng2Activity extends Activity{
	private ListView listView;
	private MyAdapter mAdapter;
	private View lineLay;
	private View mAllDownLay;
	private View mEditLay;
	public static ArrayList<HashMap<String, Object>> downLoadList;
	private List<Mp3Info> downMusicInfos;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_ing);
		
		init();
	}

	
	@Override
	protected void onPause() {
		
		GlobalValue.g_DownloadManager.setInterFace(null);
		
		super.onPause();
	}
	
	@Override
	protected void onResume() {

		GlobalValue.g_DownloadManager.setInterFace(mInterface);
		setListView();
		super.onResume();
	}


	public void init() {
		listView = (ListView) findViewById(R.id.downloading_list);
		mAllDownLay = (View) findViewById(R.id.download_alldown_lay);
		mEditLay = (View) findViewById(R.id.native_edit_lay);
		listView.setDivider(null);
		
		mAllDownLay.setOnClickListener(onClickListener);
		mEditLay.setOnClickListener(onClickListener);
		
		lineLay = LayoutInflater.from(DownLoadIng2Activity.this).inflate(R.layout.line_layout, null);
		listView.addFooterView(lineLay);
		setListView();
	}
	
	private View.OnClickListener onClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.download_alldown_lay:
			{
				GlobalValue.g_DownloadManager.allStart();
			}
				break;
			case R.id.native_edit_lay:
			{
				downMusicInfos = new ArrayList<Mp3Info>();
				
				for(int i = 0;i<downLoadList.size();i++){
					HashMap<String, Object>  map = new HashMap<String, Object>();
					map = downLoadList.get(i);
					Mp3Info mp3Info = new Mp3Info();
					
						mp3Info.setTitle(map.get(ServerAccess.MUSIC_NAME).toString());
						mp3Info.setArtist(map.get(ServerAccess.SINGER).toString());
						mp3Info.setUrl(map.get(ServerAccess.FILE_URL).toString());
						mp3Info.setId(Long.parseLong(map.get(ServerAccess.INDEX).toString()));
					downMusicInfos.add(mp3Info);
				}
				
				MusicPlayer.musicInfos = downMusicInfos;
				
				Intent intent = new Intent(DownLoadIng2Activity.this,EditListMusicActivty.class);
				intent.putExtra("activityName", "Downloadding");
				startActivity(intent);
				
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
				break;
			default:
				break;
			}
		}
	};

	private void setListView() {
		
		downLoadList = GlobalValue.g_DownloadManager.getDataList();
		
		mAdapter = new MyAdapter(DownLoadIng2Activity.this,downLoadList);
		listView.setAdapter(mAdapter);
	}
	
	private DownloadInterface mInterface = new DownloadInterface() {
		
		@Override
		public void downloadding(int index, int now, int length, boolean write) {
			mAdapter.setPro(index, length, now);
		}
		
		@Override
		public void downloadOver(int index, int length, String path) {
			
			Message msg = new Message();
			msg.what = index;
			handler.sendMessage(msg);
		}
	};
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			downLoadList = GlobalValue.g_DownloadManager.getDataList();

			mAdapter.notifyDataSetChanged();
			super.handleMessage(msg);
		}
		
	};
	
	private class MyAdapter extends BaseAdapter {
		private ArrayList<HashMap<String, Object>> list;
		private LayoutInflater mInflater;
		
		//上一次点击的MoreView
		private View mLastMore;
		
		//点击回调
		private MoreInterface moreInterface;
		
		public MyAdapter(Context context,ArrayList<HashMap<String, Object>> list) {
			this.list = list;
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		
		public void setPro(int index, int length, int now) {
			HashMap<String, Object> map = list.get(index);
			
			View view = (View)map.get("view");
			if(view != null) {
				ProgressBar bar = (ProgressBar)view.findViewById(R.id.bar);
				bar.setMax(length / 100);
				bar.setProgress(now / 100);
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			convertView = mInflater.inflate(R.layout.download_ing_list, null);
			
			TextView name = (TextView)convertView.findViewById(R.id.musicName);
			TextView singer = (TextView)convertView.findViewById(R.id.playerName);
			
			HashMap<String, Object> map = list.get(position);
			
			name.setText(map.get(ServerAccess.MUSIC_NAME).toString());
			singer.setText(map.get(ServerAccess.SINGER).toString());
			
			ProgressBar bar = (ProgressBar)convertView.findViewById(R.id.bar);
			bar.setMax(Integer.parseInt(map.get(ServerAccess.PRO_MAX).toString()));
			bar.setProgress(Integer.parseInt(map.get(ServerAccess.PRO).toString()));
			
			map.put("view", convertView);
			
			ImageView imgMore = (ImageView) convertView.findViewById(R.id.moreImg);
			
			//设置弹出菜单
			if(imgMore != null)
			{ 
				//得到弹出菜单， 将Pos储存
				View moreView = (View)convertView.findViewById(R.id.music_more_lay);
				moreView.setTag(position);
				
				//将弹出菜单存到按钮里
				imgMore.setTag(moreView);
				imgMore.setOnClickListener(moreOnClickListener);
				
				//隐藏所有弹出菜单
				moreView.setVisibility(View.GONE);
				if(mLastMore != null)
				{	
					mLastMore.setVisibility(View.GONE);
					mLastMore = null;
				}
				
				
			}
			
			return convertView;
		}
		
		//更多按下
		private View.OnClickListener moreOnClickListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				View moreView = (View)v.getTag();

				//如果上一次点击了菜单， 隐藏之
				if(mLastMore != null) {
					mLastMore.setVisibility(View.GONE);
				}
				
				int position = Integer.parseInt(moreView.getTag().toString());
				
				//添加相关点击
				Button btnStop = (Button)moreView.findViewById(R.id.onDownload_btn_stop);
				Button btnDel = (Button)moreView.findViewById(R.id.onDownload_btn_del);
				btnStop.setTag(position);
				btnDel.setTag(position);
				btnStop.setOnClickListener(stopOnClickListener);
				btnDel.setOnClickListener(delOnClickListener);
				
				//按钮状态
				if(GlobalValue.g_DownloadManager.getStartState(position)) {
					btnStop.setBackgroundDrawable(DownLoadIng2Activity.this.getResources().getDrawable(R.drawable.btn_download_start));
				}else {
					btnStop.setBackgroundDrawable(DownLoadIng2Activity.this.getResources().getDrawable(R.drawable.btn_download_close));
				}
				
				//滑动动画
				AnimaAccess anim = new AnimaAccess(DownLoadIng2Activity.this);
				moreView.startAnimation(anim.alphaAnimation(0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 200, false));
				
				moreView.setVisibility(View.VISIBLE);
				
				//储存这次按下的菜单
				mLastMore = moreView;
			}
		};
		
		//暂停按下
		private View.OnClickListener stopOnClickListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				int position = Integer.parseInt(v.getTag().toString());
				
				if(GlobalValue.g_DownloadManager.getStartState(position)) {
					GlobalValue.g_DownloadManager.stop(position);
					v.setBackgroundDrawable(DownLoadIng2Activity.this.getResources().getDrawable(R.drawable.btn_download_close));
					
				}
				else {
					GlobalValue.g_DownloadManager.start(position);
					v.setBackgroundDrawable(DownLoadIng2Activity.this.getResources().getDrawable(R.drawable.btn_download_start));
				}
				
				mLastMore.setVisibility(View.GONE);
			}
		};
		
		//删除按下
			private View.OnClickListener delOnClickListener = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					//删除提示
					
					int position = Integer.parseInt(v.getTag().toString());
					
					
					dialog(position);
					
					mLastMore.setVisibility(View.GONE);
				}
			};
			
		    protected void dialog(final int position) { 
		        AlertDialog.Builder builder = new Builder(DownLoadIng2Activity.this); 
		        builder.setMessage("确定要删除该下载吗?"); 
		        builder.setTitle("提示"); 
		        builder.setPositiveButton("删除", 
		                 
		                new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								GlobalValue.g_DownloadManager.deleteDown(position);
								
								downLoadList = GlobalValue.g_DownloadManager.getDataList();

								mAdapter.notifyDataSetChanged();
							}
		        	
		        }); 
		        builder.setNegativeButton("取消", null); 
		        builder.create().show(); 
		    } 
	}

}
